<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.dao.ProductDao" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page import="com.example.domain.Product" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="com.example.domain.CartWithProduct" %>
<%@ page import="com.example.dao.CartDao" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%
    // 检查用户是否已登录
    User currentUser = (User) session.getAttribute("user");
    if (currentUser == null) {
        response.sendRedirect("../auth/login.jsp");
        return;
    }

    // 获取选中的商品ID
    String[] selectedProductIds = request.getParameterValues("selectedItems");
    if (selectedProductIds == null || selectedProductIds.length == 0) {
        response.sendRedirect("../view/cart.jsp");
        return;
    }

    // 转换为整数数组
    List<Integer> productIdList = new ArrayList<>();
    for (String id : selectedProductIds) {
        productIdList.add(Integer.parseInt(id));
    }
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>确认订单 - 购物网</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <style>
        /* 订单流程指示器 */
        .checkout-steps {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
            padding: 1rem 0;
            background-color: var(--white-color);
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow-sm);
        }
        
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            flex: 1;
            max-width: 200px;
        }
        
        .step:not(:last-child)::after {
            content: '';
            position: absolute;
            top: 15px;
            right: -50%;
            width: 100%;
            height: 2px;
            background-color: var(--gray-300);
            z-index: 0;
        }
        
        .step-number {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: var(--gray-200);
            color: var(--gray-600);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-bottom: 0.5rem;
            position: relative;
            z-index: 1;
            transition: var(--transition);
        }
        
        .step-title {
            font-size: 0.875rem;
            color: var(--gray-600);
            text-align: center;
            transition: var(--transition);
        }
        
        .step.active .step-number {
            background-color: var(--primary-color);
            color: var(--white-color);
        }
        
        .step.active .step-title {
            color: var(--primary-color);
            font-weight: 500;
        }
        
        .step.completed .step-number {
            background-color: var(--success-color);
            color: var(--white-color);
        }
        
        .step.completed .step-title {
            color: var(--success-color);
        }
        
        .step.completed::after {
            background-color: var(--success-color);
        }
        
        /* 系统风格的信息卡片 */
        .system-card {
            background-color: var(--white-color);
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow);
            margin-bottom: 1.5rem;
            overflow: hidden;
            border-left: 4px solid var(--primary-color);
            transition: var(--transition);
        }
        
        .system-card:hover {
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
        }
        
        .system-card-header {
            background-color: var(--primary-light);
            padding: 1rem 1.5rem;
            font-weight: 600;
            color: var(--primary-color);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .system-card-body {
            padding: 1.5rem;
        }
        
        /* 系统风格的表单 */
        .system-form .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.25rem;
            margin-bottom: 1.25rem;
        }
        
        .system-form .form-group {
            margin-bottom: 0;
        }
        
        .system-form label {
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .system-form input,
        .system-form textarea,
        .system-form select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--gray-300);
            border-radius: var(--border-radius);
            font-size: 1rem;
            background-color: var(--white-color);
            transition: var(--transition);
        }
        
        .system-form input:focus,
        .system-form textarea:focus,
        .system-form select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(66, 99, 235, 0.1);
        }
        
        .system-form input:disabled,
        .system-form textarea:disabled,
        .system-form select:disabled {
            background-color: var(--gray-50);
            color: var(--gray-500);
            border-color: var(--gray-200);
        }
        
        /* 系统风格的表格 */
        .system-table {
            width: 100%;
            border-collapse: collapse;
            background-color: var(--white-color);
            border-radius: var(--border-radius-lg);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            margin-bottom: 1.5rem;
        }
        
        .system-table thead {
            background-color: var(--gray-50);
        }
        
        .system-table th {
            padding: 1rem 1.25rem;
            text-align: left;
            font-weight: 600;
            color: var(--gray-700);
            border-bottom: 2px solid var(--border-color);
        }
        
        .system-table td {
            padding: 1rem 1.25rem;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }
        
        .system-table tbody tr:last-child td {
            border-bottom: none;
        }
        
        .system-table tbody tr:hover {
            background-color: var(--gray-50);
        }
        
        /* 系统风格的价格摘要 */
        .price-summary {
            background-color: var(--gray-50);
            border-radius: var(--border-radius-lg);
            padding: 1.5rem;
            border: 1px solid var(--border-color);
        }
        
        .summary-header {
            font-weight: 600;
            color: var(--gray-800);
            margin-bottom: 1rem;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid var(--border-color);
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            color: var(--gray-700);
            font-size: 0.95rem;
        }
        
        .summary-row.total {
            font-weight: 700;
            font-size: 1.1rem;
            color: var(--primary-color);
            margin-top: 0.5rem;
            padding-top: 1rem;
            border-top: 1px solid var(--border-color);
        }
        
        /* 系统操作按钮 */
        .system-actions {
            display: flex;
            gap: 1rem;
            margin-top: 2rem;
            justify-content: flex-end;
        }
        
        .system-btn {
            padding: 0.875rem 1.5rem;
            border-radius: var(--border-radius);
            font-weight: 600;
            font-size: 1rem;
            transition: var(--transition);
            border: none;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .system-btn-primary {
            background-color: var(--primary-color);
            color: var(--white-color);
        }
        
        .system-btn-primary:hover {
            background-color: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }
        
        .system-btn-secondary {
            background-color: var(--gray-200);
            color: var(--gray-800);
        }
        
        .system-btn-secondary:hover {
            background-color: var(--gray-300);
        }
        
        /* 系统提示信息 */
        .system-alert {
            padding: 1rem 1.25rem;
            border-radius: var(--border-radius);
            margin-bottom: 1rem;
            border-left: 4px solid;
            background-color: var(--gray-50);
        }
        
        .system-alert.info {
            border-left-color: var(--primary-color);
            color: var(--gray-800);
        }
        
        .system-alert.warning {
            border-left-color: var(--warning-color);
            color: var(--gray-800);
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .checkout-steps {
                padding: 0.75rem 0;
            }
            
            .step-title {
                font-size: 0.75rem;
            }
            
            .system-form .form-row {
                grid-template-columns: 1fr;
                gap: 1rem;
            }
            
            .system-table th,
            .system-table td {
                padding: 0.75rem;
                font-size: 0.9rem;
            }
            
            .system-actions {
                flex-direction: column;
            }
            
            .system-btn {
                width: 100%;
                justify-content: center;
            }
        }
        
        @media (max-width: 480px) {
            .system-card-body {
                padding: 1rem;
            }
            
            .price-summary {
                padding: 1rem;
            }
        }
        
        /* 商品信息展示优化 */
        .product-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .product-image-small {
            width: 60px;
            height: 60px;
            border-radius: var(--border-radius);
            background-color: var(--gray-100);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        
        .product-image-small img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .product-details {
            flex: 1;
        }
        
        .product-name {
            font-weight: 500;
            color: var(--gray-800);
            margin-bottom: 0.25rem;
        }
        
        .product-sku {
            font-size: 0.875rem;
            color: var(--gray-500);
        }
        
        /* 加载动画 */
        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: var(--white-color);
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="header-nav">
        <div class="nav-container">
            <a href="../index.jsp" class="nav-brand">
                🛒 购物网管理系统
            </a>
            
            <!-- 搜索框 -->
            <div style="flex: 1; max-width: 400px; margin: 0 20px; position: relative;">
                <input type="text" placeholder="搜索商品..." style="width: 100%; padding: 10px 15px; padding-right: 40px; border-radius: var(--border-radius); border: 1px solid var(--gray-300); transition: var(--transition);">
                <button style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--gray-500); cursor: pointer; font-size: 1.2rem;">
                    🔍
                </button>
            </div>
            
            <ul class="nav-links">
                <li><a href="../index.jsp">首页</a></li>
                <li><a href="../products/list.jsp">商品管理</a></li>
                <li><a href="../view/cart.jsp">购物车</a></li>
                <% if (currentUser != null) { %>
                    <li><a href="../admin/user_info.jsp">用户中心</a></li>
                <% } %>
            </ul>
            
            <div class="user-actions">
                <% if (currentUser != null) { %>
                    <span class="user-info">用户: <%= currentUser.getUsername() %> | 角色: 普通用户</span>
                    <a href="../auth/logout.jsp" class="btn btn-outline">退出登录</a>
                <% } else { %>
                    <a href="../auth/login.jsp" class="btn btn-outline">登录</a>
                    <a href="../auth/register.jsp" class="btn" style="margin-left: 10px;">注册</a>
                <% } %>
            </div>
        </div>
    </nav>
    
    <!-- 系统页面头部 -->
    <div class="container">
        <div class="page-header" style="background-color: var(--primary-light); border-bottom: 1px solid var(--border-color); padding: 1.5rem 0; margin-bottom: 2rem;">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="page-title" style="color: var(--primary-color); font-size: 1.75rem; margin: 0;">订单确认</h1>
                    <p style="color: var(--gray-600); margin-top: 0.25rem;">订单编号: <span style="font-family: monospace;">ORD<%= new Date().getTime() %></span> | 操作时间: <span style="font-family: monospace;"><%= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) %></span></p>
                </div>
                <div>
                    <a href="../view/cart.jsp" class="btn btn-outline">
                        ← 返回购物车
                    </a>
                </div>
            </div>
        </div>
        
        <!-- 订单流程指示器 -->
        <div class="checkout-steps">
            <div class="step completed">
                <div class="step-number">1</div>
                <div class="step-title">购物车</div>
            </div>
            <div class="step active">
                <div class="step-number">2</div>
                <div class="step-title">确认订单</div>
            </div>
            <div class="step">
                <div class="step-number">3</div>
                <div class="step-title">支付</div>
            </div>
            <div class="step">
                <div class="step-number">4</div>
                <div class="step-title">完成</div>
            </div>
        </div>
    
    <!-- 通知消息 -->
    <div id="notification" class="notification"></div>
    
    <div class="container">
        <% 
            Connection conn = null;
            double totalAmount = 0;
            List<CartWithProduct> selectedItems = new ArrayList<>();
            
            try {
                conn = DBUtil.getConnection();
                CartDao cartDao = new CartDao();
                ProductDao productDao = new ProductDao();
                
                // 获取用户购物车中的选中商品
                List<CartWithProduct> cartItems = cartDao.getCartListByMemberId(currentUser.getId());
                
                for (CartWithProduct item : cartItems) {
                    if (productIdList.contains(item.getProduct_id())) {
                        selectedItems.add(item);
                        totalAmount += item.getSale_money();
                    }
                }
                
                if (selectedItems.isEmpty()) {
        %>
            <div class="card" style="padding: 3rem; text-align: center;">
                <h3>没有选中商品</h3>
                <p style="margin: 1rem 0;">请先选择要购买的商品</p>
                <a href="../view/cart.jsp" class="btn btn-outline">返回购物车</a>
            </div>
        <% } else { %>
        <form id="orderForm" action="../order/process.jsp" method="post">
            <div class="row" style="display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem;">
                <div>
                    <!-- 收货信息卡片 -->
                    <div class="system-card">
                        <div class="system-card-header">
                            📋 收货信息
                        </div>
                        <div class="system-card-body">
                            <div class="system-form">
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="recipient">收货人</label>
                                        <input type="text" id="recipient" value="<%= currentUser.getUsername() %>" readonly class="form-control">
                                    </div>
                                    <div class="form-group">
                                        <label for="phone">联系电话</label>
                                        <input type="text" id="phone" value="<%= currentUser.getPhone() != null ? currentUser.getPhone() : "" %>" readonly class="form-control">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="address">收货地址</label>
                                    <textarea id="address" readonly style="resize: vertical; min-height: 80px;" class="form-control"><%= currentUser.getAddress() != null && !currentUser.getAddress().isEmpty() ? currentUser.getAddress() : "暂无地址信息，请到个人中心完善" %></textarea>
                                    <div class="address-edit-tip" onclick="window.location.href='../admin/user_info.jsp'" style="margin-top: 0.5rem; font-size: 0.9rem; color: var(--primary-color); cursor: pointer; display: inline-flex; align-items: center; gap: 0.25rem;">
                                        📝 修改地址信息
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 商品信息卡片 -->
                    <div class="system-card">
                        <div class="system-card-header">
                            🛍️ 商品信息
                        </div>
                        <div class="system-card-body">
                            <table class="system-table">
                                <thead>
                                    <tr>
                                        <th style="width: 50%;">商品</th>
                                        <th>单价</th>
                                        <th>数量</th>
                                        <th>小计</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <% for (CartWithProduct item : selectedItems) { %>
                                    <tr>
                                        <td>
                                            <div class="product-info">
                                                <div class="product-image-small">
                                                    <% if (item.getProduct_image() != null && !item.getProduct_image().isEmpty()) { %>
                                                        <img src="../uploads/products/<%= item.getProduct_image() %>" alt="<%= item.getProduct_name() %>">
                                                    <% } else { %>
                                                        <img src="../assets/images/no-image.svg" alt="暂无图片" style="width: 30px; height: 30px;">
                                                    <% } %>
                                                </div>
                                                <div class="product-details">
                                                    <div class="product-name"><%= item.getProduct_name() %></div>
                                                    <div class="product-sku">SKU: <%= item.getProduct_id() %></div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="text-right" style="font-family: monospace;">¥<%= String.format("%.2f", item.getSale_price()) %></td>
                                        <td class="text-center">×<%= item.getSale_num() %></td>
                                        <td class="text-right" style="color: var(--primary-color); font-weight: 600; font-family: monospace;">¥<%= String.format("%.2f", item.getSale_money()) %></td>
                                    </tr>
                                    <input type="hidden" name="selectedItems" value="<%= item.getProduct_id() %>">
                                    <% } %>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧订单摘要 -->
                <div>
                    <div class="system-card">
                        <div class="system-card-header">
                            💰 订单摘要
                        </div>
                        <div class="system-card-body">
                            <div class="price-summary">
                                <div class="summary-header">订单信息</div>
                                
                                <div class="system-alert info" style="margin-bottom: 1.5rem;">
                                    <strong>提示：</strong>请仔细核对订单信息，确认无误后提交。
                                </div>
                                
                                <div class="summary-row">
                                    <span>商品总额</span>
                                    <span style="font-family: monospace;">¥<%= String.format("%.2f", totalAmount) %></span>
                                </div>
                                
                                <div class="summary-row">
                                    <span>优惠折扣</span>
                                    <span style="font-family: monospace; color: var(--success-color);">-¥0.00</span>
                                </div>
                                
                                <div class="summary-row">
                                    <span>运费</span>
                                    <span style="font-family: monospace;">+¥0.00</span>
                                </div>
                                
                                <div class="summary-row total">
                                    <span>应付总额</span>
                                    <span style="font-family: monospace; font-size: 1.25rem;">¥<%= String.format("%.2f", totalAmount) %></span>
                                </div>
                                
                                <div style="margin-top: 1.5rem; padding: 1rem; background-color: var(--gray-50); border-radius: var(--border-radius);">
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                                        <span style="font-weight: 500; color: var(--gray-700);">商品数量</span>
                                        <span style="color: var(--gray-700);"><%= selectedItems.size() %> 件</span>
                                    </div>
                                    <div style="display: flex; justify-content: space-between; align-items: center;">
                                        <span style="font-weight: 500; color: var(--gray-700);">订单状态</span>
                                        <span style="color: var(--warning-color);">待提交</span>
                                    </div>
                                </div>
                                
                                <div style="margin-top: 2rem;">
                                    <button type="submit" class="system-btn system-btn-primary" id="submitBtn" style="width: 100%;">
                                        <span id="btnText">提交订单</span>
                                        <span id="loading" class="loading-spinner" style="display: none;"></span>
                                    </button>
                                    
                                    <div style="text-align: center; margin-top: 1rem; font-size: 0.875rem; color: var(--gray-500);">
                                        提交即表示您同意<a href="#" style="color: var(--primary-color); text-decoration: underline;">用户协议</a>和<a href="#" style="color: var(--primary-color); text-decoration: underline;">隐私政策</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
        <% 
                }
            } catch (Exception e) {
        %>
        <div class="card" style="padding: 2rem; text-align: center; color: var(--danger-color);">
            <p>加载订单信息失败: <%= e.getMessage() %></p>
        </div>
        <% 
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (Exception e) {
                        // 忽略关闭连接的异常
                    }
                }
            }
        %>
    </div>
    
    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-top">
                <div>
                    <a href="../index.jsp" class="footer-logo">🛒 购物网</a>
                    <p style="margin-top: 1rem; color: var(--gray-400); font-size: 0.9rem;">
                        优质商品，优质服务，打造您的理想购物体验。
                    </p>
                </div>
                
                <div>
                    <h4 class="footer-heading">快速链接</h4>
                    <ul class="footer-links">
                        <li><a href="../index.jsp">首页</a></li>
                        <li><a href="../products/list.jsp">商品浏览</a></li>
                        <li><a href="#">关于我们</a></li>
                        <li><a href="#">联系我们</a></li>
                    </ul>
                </div>
                
                <div>
                    <h4 class="footer-heading">客户服务</h4>
                    <ul class="footer-links">
                        <li><a href="#">帮助中心</a></li>
                        <li><a href="#">售后政策</a></li>
                        <li><a href="#">配送信息</a></li>
                        <li><a href="#">常见问题</a></li>
                    </ul>
                </div>
            </div>
            
            <div class="footer-bottom">
                <p>&copy; 2025 购物网. 保留所有权利.</p>
            </div>
        </div>
    </footer>
    
    <script>
        // 显示通知消息
        function showNotification(message, isSuccess) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification ' + (isSuccess ? 'success' : 'error');
            notification.style.display = 'block';
            
            setTimeout(() => {
                notification.style.animation = 'slideInRight 0.3s ease-in reverse';
                setTimeout(() => {
                    notification.style.display = 'none';
                }, 300);
            }, 3000);
        }
        
        // 表单提交处理
        document.getElementById('orderForm').addEventListener('submit', function(event) {
            // 显示加载状态
            const submitBtn = document.getElementById('submitBtn');
            const btnText = document.getElementById('btnText');
            const loading = document.getElementById('loading');
            
            submitBtn.disabled = true;
            btnText.textContent = '提交中';
            loading.style.display = 'inline-block';
            
            // 显示提交提示
            showNotification('系统正在处理您的订单...', true);
            
            // 由于process.jsp返回的是JSON，我们需要使用AJAX来处理提交
            event.preventDefault();
            
            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();
            
            xhr.open('POST', this.action, true);
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            // 订单创建成功，跳转到成功页面
                            showNotification('订单提交成功，正在跳转...', true);
                            setTimeout(() => {
                                window.location.href = '../order/success.jsp';
                            }, 1500);
                        } else {
                            // 订单创建失败
                            showNotification('错误: ' + response.message, false);
                            resetButtonState();
                        }
                    } catch (e) {
                        // 处理JSON解析错误
                        showNotification('系统错误: 订单处理异常，请稍后重试', false);
                        resetButtonState();
                    }
                } else {
                    // 网络错误
                    showNotification('系统错误: 网络连接异常，请稍后重试', false);
                    resetButtonState();
                }
            };
            
            xhr.onerror = function() {
                showNotification('系统错误: 网络连接失败，请检查网络设置', false);
                resetButtonState();
            };
            
            // 重置按钮状态
            function resetButtonState() {
                submitBtn.disabled = false;
                btnText.textContent = '提交订单';
                loading.style.display = 'none';
            }
            
            xhr.send(formData);
        });
        
        // 添加页面加载动画
        window.addEventListener('load', function() {
            document.body.classList.add('loaded');
        });
    </script>
</body>
</html>